import 'dart:async';
import 'dart:convert';

import 'package:crypto/crypto.dart';
import 'package:fish_redux/fish_redux.dart';
import 'package:flutter/material.dart' hide Action;
import 'package:fluttertoast/fluttertoast.dart';
import 'package:hayll_app_village_master/hayll/network/yll_network.dart';
import 'package:hayll_app_village_master/hayll/village_manager/login/bean/login_result.dart';
import 'package:hayll_app_village_master/hayll/village_manager/network/village_action.dart';
import 'action.dart';
import 'state.dart';

import 'package:shared_preferences/shared_preferences.dart';

Effect<LoginState> buildEffect() {
  return combineEffects(<Object, Effect<LoginState>>{
    LoginAction.reloadLoggingInfo: _reloadLoginInfo,
    LoginAction.login: _onLogin,
    LoginAction.sendSMSCode: _sendSMSCode,
    Lifecycle.appear:_reloadLoginInfo,
    Lifecycle.initState:_reloadLoginInfo,
  });
}

void _sendSMSCode(Action action, Context<LoginState> ctx) async {
  Map<String, dynamic> params = {
    'phone': ctx.state.textTelephoneView.text,
    'type': 1,

    /// 1：登录验证码, 2：绑定验证码，3：支付验证码
  };
  // YllNetwork.requestPost(VillageAction.getVerifySmsCode, params: params,
  //     success: (json) {
  //   if (json['data'] == true) {
  //     Fluttertoast.showToast(msg: '发送成功');
  //     //倒计时
  //     ctx.state.currCountTime = 60;
  //     Timer.periodic(Duration(seconds: 1), (timer) {
  //       if (ctx.state.currCountTime <= 0) {
  //         timer.cancel();
  //       } else {
  //         ctx.state.currCountTime--;
  //         ctx.dispatch(LoginActionCreator.onSendSmsCowndown());
  //       }
  //     });
  //   } else {
  //     Fluttertoast.showToast(msg: '发送失败');
  //   }
  // }, failed: (errorCode, errorMsg) {
  //   Fluttertoast.showToast(msg: '$errorCode,$errorMsg');
  // });
}

void _onLogin(Action action, Context<LoginState> ctx) async {
  /**2-验证码,3-微信,4-QQ,5-微博,6-支付宝*/
  var params = {
    // 'loginType': 2,
    // 'weixinId': '',
    'phone': ctx.state.textTelephoneView.text,
    'password': md5.convert(Utf8Encoder().convert(ctx.state.textVerifyCodeView.text)).toString(),
    // 'type': 1,
  };
  YllNetwork.requestPost(VillageAction.login, params: params, success: (json) {
    var result = LoginResult.fromJson(json);
    result.password = ctx.state.textVerifyCodeView.text;//返回的密码是密文，需要改成明文保存
    _saveLastLoginInfo(result);
    Navigator.pushReplacementNamed(ctx.context,'/home');
  }, failed: (errorCode, errorMsg) {
    Fluttertoast.showToast(msg: '$errorCode,$errorMsg');
  });

  //记录上一次输入的手机号
  var sp = await SharedPreferences.getInstance();
  sp.setString('lastLoginTelephone', ctx.state.textTelephoneView.text);
}

void _saveLastLoginInfo(LoginResult loginInfo) async {
  var sp = await SharedPreferences.getInstance();
  sp.setString('lastLoginTelephone', loginInfo.phone);
  sp.setString('loginingToken', loginInfo.token);
  sp.setInt('loginingUserId', loginInfo.userId);
  sp.setInt('lastLoginTime', DateTime.now().millisecondsSinceEpoch);
  
  sp.setString('loginingUserNickName', loginInfo.roleName);
  sp.setString('loginingUserName', loginInfo.userName);
  sp.setString('pwd', loginInfo.password);
  //缓存到登录账号中
  _setLoginingCache(loginInfo.token, loginInfo.userId, loginInfo.phone);
}

void _setLoginingCache(String token,int userId,String phone){
  YllNetwork.setLoginCache(token, userId, phone);
}

void _reloadLoginInfo(Action action, Context<LoginState> ctx) async {
  var sp = await SharedPreferences.getInstance();
  var phone = await sp.getString('lastLoginTelephone');
  var token = await sp.getString('loginingToken');
  var loginingUserId = await sp.getInt('loginingUserId');
  var lastLoginTime = await sp.getInt('lastLoginTime');
  var pwd = await sp.getString('pwd');
  //if
  // if (token != null &&
  //     DateTime.now().millisecondsSinceEpoch - lastLoginTime <
  //         15 * 24 * 3600 * 1000) {
  //   //登录状态
  //   Navigator.of(ctx.context).pushReplacementNamed('/home');
  // } else {
    //刷新界面
    ctx.dispatch(Action(LoginAction.refreshUI, payload: {'phone':phone,'pwd':pwd}));
  // }
}
